import 'dart:convert';

import 'package:agent_process_app/pages/mine_screen.dart';
import 'package:agent_process_app/pages/mydrawer.dart';
import 'package:agent_process_app/pages/step_screen.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:agent_process_app/utils/myUtils.dart' as myUtils;

//源码注释 : 在整个应用程序中唯一的键。
final GlobalKey<ScaffoldState> _scaffoldstate = GlobalKey<ScaffoldState>();

class HomeScreen extends StatefulWidget {
    @override
    State<StatefulWidget> createState() {
        return Projects();
    }
}

class Projects extends State<HomeScreen> {
    final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
    new GlobalKey<RefreshIndicatorState>();

    var projectList = new List<Widget>();

    //在底部弹出的提示
    void _showSnackBar(String value) {
//    if(value.isEmpty) return;
        _scaffoldstate.currentState.showSnackBar(SnackBar(
            duration: Duration(milliseconds: 1000),
            content: Text(value),
        ));
    }

    refreshProjectList() async {
        String token;
        await myUtils.LocalStorage.getLocalStorageInstance()
                .then((SharedPreferences sharedPreferences) {
            token = sharedPreferences.getString("token");
        });

        Dio dio = myUtils.MyDio.getDio(token);
        Response response;
        try {
            response = await dio.get(
                "/projects",
            );
//            print(response.statusCode);
//            print(response.data);
            int statusCode = response.data["Code"];
            List<dynamic> dataList = response.data["Data"];
            if (dataList == null) {
                _showSnackBar("没有找到与您相关的项目,点击右下角添加按钮进行添加!");
            }

            if (statusCode == 200) {
                //渲染列表
                projectList.clear();
                setState(() {
                    projectList = List.generate(
                            dataList.length,
                                    (i) =>
                                    ListTile(
                                        title: Text(dataList[i]["Name"]),
                                        subtitle: Text(
                                                dataList[i]["FullAddress"]),
                                        trailing: dataList[i]["Status"] == 0
                                                ? Icon(
                                            Icons.bookmark,
                                            color: Colors.red,
                                        )
                                                : Icon(
                                            Icons.check,
                                            color: Colors.green,
                                        ),
                                        onTap: () {
                                            Navigator.push(context,
                                                    new MaterialPageRoute(
                                                            builder: (
                                                                    BuildContext context) {
                                                                return new StepScreen(
                                                                        dataList[i]["Name"]);
                                                            }));
                                        },
                                    ));
                });

                _showSnackBar("刷新成功!");
            } else if (statusCode == 500) {
                _showSnackBar("对不起,您的操作出异常了!");
            } else if (statusCode == 403) {
                _showSnackBar("对不起,登录已过期,需要重新登录,将在3秒后进入登录页面!");
                SharedPreferences s = await SharedPreferences.getInstance();
                //延迟3秒后退出到登录页面
                Future.delayed(new Duration(seconds: 3), () {
                    myUtils.MyUtils.clearUserInfo();
                    Navigator.of(context).pushNamedAndRemoveUntil(
                            "/loginScreen", (route) => route == null);
                });
            }
            print(response.data);
        } catch (e) {
            print(e);
            print("网络错误!");
            _showSnackBar("请检查您的网络是否正常!");
        }
    }

    //渲染项目列表
    Widget renderProjectList(context, index) {
        return projectList[index];
    }

    @override
    void initState() {
        // TODO: implement initState
        super.initState();
        // 刷新项目列表
        refreshProjectList();
    }

    @override
    Widget build(BuildContext context) {
        // TODO: implement build
        return Scaffold(
                key: _scaffoldstate,
                floatingActionButton: FloatingActionButton(
                    onPressed: () {},
                    child: Icon(Icons.add),
                    tooltip: "添加项目",
                ),
                appBar: AppBar(
                    title: Text("项目列表"),
                    centerTitle: true,
//                actions: <Widget>[
//                    IconButton(
//                        icon: Icon(Icons.search),
//                        tooltip: "搜索项目",
//                        onPressed: () {},
//                    ),
//                ],
                ),
                drawer: MyDrawer(),
                body: Scrollbar(
                        child: RefreshIndicator(
                            key: _refreshIndicatorKey,
                            onRefresh: () {
                                print('refresh');
                                return refreshProjectList();
                            },
                            child: ListView.builder(
                                physics: AlwaysScrollableScrollPhysics(),
                                itemCount: projectList.length,
                                itemBuilder: renderProjectList,
                            ),
                        )));
    }
}
